#!/usr/bin/env python
import os
import sys
import traceback
import django
from django.core.management import execute_from_command_line
from django.conf import settings

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings_mes_basic')
sys.path.insert(0, '/home/ubuntu/zlymes/mesmaster')

def check_imports():
    """检查关键模块的导入"""
    print("=== 检查关键模块导入 ===")
    
    # 检查Django核心组件
    try:
        import django
        print(f"✓ Django version: {django.get_version()}")
    except Exception as e:
        print(f"✗ Django导入失败: {e}")
        return False
    
    # 检查设置文件
    try:
        from django.conf import settings
        print(f"✓ Settings loaded: {settings.SETTINGS_MODULE}")
    except Exception as e:
        print(f"✗ Settings导入失败: {e}")
        return False
    
    return True

def check_database():
    """检查数据库连接"""
    print("\n=== 检查数据库连接 ===")
    try:
        from django.db import connection
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
            result = cursor.fetchone()
            print(f"✓ 数据库连接成功: {result}")
        return True
    except Exception as e:
        print(f"✗ 数据库连接失败: {e}")
        return False

def check_apps():
    """检查应用模块"""
    print("\n=== 检查应用模块 ===")
    try:
        django.setup()
        from django.apps import apps
        installed_apps = apps.get_app_configs()
        print(f"✓ 已安装应用数量: {len(installed_apps)}")
        for app in installed_apps:
            print(f"  - {app.name}")
        return True
    except Exception as e:
        print(f"✗ 应用检查失败: {e}")
        print(f"错误详情: {traceback.format_exc()}")
        return False

def check_models():
    """检查模型定义"""
    print("\n=== 检查模型定义 ===")
    try:
        from django.apps import apps
        all_models = apps.get_models()
        print(f"✓ 已加载模型数量: {len(all_models)}")
        for model in all_models:
            print(f"  - {model._meta.app_label}.{model._meta.model_name}")
        return True
    except Exception as e:
        print(f"✗ 模型检查失败: {e}")
        print(f"错误详情: {traceback.format_exc()}")
        return False

def run_migrations():
    """运行数据库迁移"""
    print("\n=== 运行数据库迁移 ===")
    try:
        execute_from_command_line(['manage.py', 'migrate', '--noinput'])
        print("✓ 数据库迁移完成")
        return True
    except Exception as e:
        print(f"✗ 数据库迁移失败: {e}")
        print(f"错误详情: {traceback.format_exc()}")
        return False

def create_superuser():
    """创建超级用户"""
    print("\n=== 创建超级用户 ===")
    try:
        from django.contrib.auth.models import User
        if not User.objects.filter(username='admin').exists():
            User.objects.create_superuser('admin', 'admin@example.com', 'admin123')
            print("✓ 超级用户创建成功")
        else:
            print("✓ 超级用户已存在")
        return True
    except Exception as e:
        print(f"✗ 超级用户创建失败: {e}")
        print(f"错误详情: {traceback.format_exc()}")
        return False

def start_server():
    """启动开发服务器"""
    print("\n=== 启动开发服务器 ===")
    try:
        execute_from_command_line(['manage.py', 'runserver', '0.0.0.0:8004'])
        return True
    except Exception as e:
        print(f"✗ 服务器启动失败: {e}")
        print(f"错误详情: {traceback.format_exc()}")
        return False

if __name__ == '__main__':
    print("Django MES 系统启动调试")
    print("=" * 50)
    
    # 执行各项检查
    checks = [
        check_imports,
        check_apps,
        check_database,
        check_models,
        run_migrations,
        create_superuser,
    ]
    
    for check_func in checks:
        if not check_func():
            print(f"\n❌ 检查失败，停止启动流程")
            sys.exit(1)
    
    print("\n✅ 所有检查通过，启动服务器...")
    start_server() 